<template>
  <div class="app-container">
    <el-form :model="queryParams" :disabled="loading" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="培训主题" prop="trainTheme">
        <el-input
          v-model="queryParams.trainTheme"
          placeholder="请输入培训主题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:train:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:train:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:train:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="trainList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="培训主题" align="center" prop="trainTheme" />
      <el-table-column label="培训时间" align="center" prop="trainTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.trainTime, '{y}-{m}-{d} {h}:{m}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="培训地点" align="center" prop="address" />
      <el-table-column label="培训对象" align="center" prop="trainObject" />
      <el-table-column label="培训师资" align="center" prop="trainTeachers" />
      <el-table-column label="培训学时" align="center" prop="trainHours" />
      <el-table-column label="创建人" align="center" prop="createrName" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{m}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作人" align="center" prop="operterName" />
      <el-table-column label="操作时间" align="center" prop="operTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.operTime, '{y}-{m}-{d} {h}:{m}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:train:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:train:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改教育培训对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="培训主题" prop="trainTheme">
          <el-input v-model="form.trainTheme" placeholder="请输入培训主题" />
        </el-form-item>
        <el-form-item label="培训时间" prop="trainTime">
          <el-date-picker clearable
            v-model="form.trainTime"
            type="datetime"
            value-format="yyyy-MM-dd hh:mm:ss"
            placeholder="请选择培训时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="培训地点" prop="address">
          <el-input v-model="form.address" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="培训对象" prop="trainObject">
          <el-input v-model="form.trainObject" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="培训师资" prop="trainTeachers">
          <el-input v-model="form.trainTeachers" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="培训学时" prop="trainHours">
          <el-input v-model="form.trainHours" placeholder="请输入培训学时" />
        </el-form-item>
        <el-form-item label="签到表" prop="signInTable">
          <el-upload
            :action="uploadUrl"
            :file-list="form.signInTable"
            :on-success="(res, file, fileList) => uploadImgSuccess(res, file, fileList, 'signInTable')"
            :on-preview="uploadPreview"
            :before-upload="file => uploadBefore(file, 'signInTable')"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">文件大小不能超过5M</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="培训课件" prop="courseware">
          <el-upload
            :action="uploadUrl"
            :file-list="form.courseware"
            :on-success="(res, file, fileList) => uploadImgSuccess(res, file, fileList, 'courseware')"
            :before-upload="file => uploadBefore(file, 'courseware')"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">文件大小不能超过5M</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="考评结果" prop="result">
          <el-upload
            :action="uploadUrl"
            :file-list="form.result"
            :on-success="(res, file, fileList) => uploadImgSuccess(res, file, fileList, 'result')"
            :before-upload="file => uploadBefore(file, 'result')"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">文件大小不能超过5M</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTrain, getTrain, delTrain, addTrain, updateTrain } from "@/api/system/train";
import {uploadUrl, uploadFile, rootPath} from "@/api/system/config";

export default {
  name: "Train",
  data() {
    return {
      uploadUrl,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 教育培训表格数据
      trainList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        trainTime: null,
        address: null,
        trainObject: null,
        trainTheme: null,
        trainTeachers: null,
        trainHours: null,
        creater: null,
        operter: null,
        operTime: null
      },
      // 表单参数
      form: {
        signInTable: [],
        courseware: [],
        result: []
      },
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    uploadPreview(file) {
      console.log('file', file)
      window.open(rootPath + file.fileUrl, '_blank');
    },
    uploadBefore(file, type) {
      console.log('file', file)
      const isLt2M = file.size / 1024 / 1024 < 5;

      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 5MB!');
      }
      return isLt2M;
    },
    uploadImgSuccess(res, file, fileList, type) {
      console.log('res', res, file, fileList)
      let typeTmp
      switch (type) {
        case 'signInTable':
          typeTmp = 1
          break
        case 'courseware':
          typeTmp = 2
          break
        case 'result':
          typeTmp = 3
          break
        default:
      }
      this.form[type] = [
        ...this.form[type],
        ...[
          {
            name: res.originalFilename,
            fileType: typeTmp,
            url: res.url,
            fileUrl: res.fileName
          }
        ]
      ]
    },
    /** 查询教育培训列表 */
    getList() {
      this.loading = true;
      listTrain(this.queryParams).then(response => {
        this.trainList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        trainTime: null,
        address: null,
        trainObject: null,
        trainTheme: null,
        trainTeachers: null,
        trainHours: null,
        creater: null,
        createTime: null,
        operter: null,
        operTime: null,
        signInTable: [],
        courseware: [],
        result: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加教育培训";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getTrain(id).then(response => {
        this.form = response.data;
        this.form.signInTable = []
        this.form.courseware = []
        this.form.result = []
        for(let i = 0; i < this.form.fileList.length; i++) {
          const fileItem = this.form.fileList[i]
          if (!fileItem.fileUrl) continue
          const tmpArr = fileItem.fileUrl.split('/')
          fileItem.name = tmpArr[tmpArr.length - 1]
          const tmpArr1 = fileItem.name.split('.')
          fileItem.extname = tmpArr1[tmpArr1.length - 1]
          fileItem.url = rootPath + fileItem.fileUrl
          if (this.form.fileList[i].fileType === 1) {
            this.form.signInTable = [
              ...this.form.signInTable,
              ...[fileItem]
            ]
          }
          if (this.form.fileList[i].fileType === 2) {
            this.form.courseware = [
              ...this.form.courseware,
              ...[fileItem]
            ]
          }
          if (this.form.fileList[i].fileType === 3) {
            this.form.result = [
              ...this.form.result,
              ...[fileItem]
            ]
          }
        }
        this.open = true;
        this.title = "修改教育培训";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.fileList = []
          this.form.fileList = [
            ...this.form.signInTable,
            ...this.form.courseware,
            ...this.form.result
          ]
          if (this.form.id != null) {
            updateTrain(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTrain(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除教育培训编号为"' + ids + '"的数据项？').then(function() {
        return delTrain(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/train/export', {
        ...this.queryParams
      }, `train_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
